/**
 * Created by gray on 2019/7/25.
 */
/**
 * Created by gray on 2019/7/25.
 */
/**
 * utils.js
 *
 * @NAmdConfig ./configuration.json
 * @NApiVersion 2.x
 */
define(
    ['N/record','N/search'],
    function(record,search) {

        var method = {};

        //让json支持  obj['obj.obj.obj']写法
        method.getJSONElementValue = function(obj,keyStr){
            var keys = keyStr.split(".");
            var object = obj;
            var key;
            for(var i=0;i<keys.length;i++){
                key = keys[i];
                object = object[key];
                if(i==keys.length-1){
                    return object;
                }
            }
        }

        /*
         * 根据货币名称拿到在NS里的id
         * */
        method.getCurrencyIdByName = function(currencyName){
            if(!currencyName){
                return ;
            }
            var ids ;
            search.create({
                type: search.Type.CURRENCY,
                title: 'test',
                columns: ['name','symbol'],
                filters: [['symbol','is',currencyName]]
            }).run().each(function(ctx){
                ids = ctx.id;
            });

            if(!ids){
                search.create({
                    type: search.Type.CURRENCY,
                    title: 'test',
                    columns: ['name','symbol'],
                    filters: [['name','is',currencyName]]
                }).run().each(function(ctx){
                    ids = ctx.id;
                });
            }
            if(!ids){
                throw "this currency ["+currencyName+"] not in NetSuite !"
            }
            return ids;
        };

        /*
         * fromCurrency id
         * toCurrency id
         * */
        method.getCurrencyRate = function(fromCurrency,toCurrency){
            if(fromCurrency,toCurrency) {
                try {
                    var mySearch = search.create({
                        type: 'currencyrate',
                        columns: [{"name": "exchangerate", "type": "float", "sortdir": "ASC"}],
                        filters: [["basecurrency", "anyof", fromCurrency], 'AND', ['transactioncurrency', 'any', toCurrency]]
                    }).run().each(function (ctx) {
                        var rate = ctx.getValue('exchangerate');
                        if (rate) {
                            return parseFloat(rate);
                        }
                    });
                } catch (e) {
                }
            }
            return 1.0;
        }
        /*
         * 根据套件名称/id拿到关联商品详情。(入参只能填一个)
         * @return
         * [{
         *   "sku":"sku",
         *   "internalid":"internalid",
         *   "type":"type",
         *   "quantity":123
         * }]
         * */
        method.kit = new Object();
        method.kit.getItemDeatilsByKitName = function(akitId,akitNames){
            if(akitId==null&&akitNames==null){
                return null;
            }else if(akitId!=null&&akitNames!=null){
                return null;
            }

            var kitId = akitId;
            if(akitNames){
                try{
                    kitId = search.create({
                        type:'kititem',
                        title:"test",
                        columns: [],
                        filters: [['itemid', 'is', akitNames]]
                    }).run().getRange({start:0,end:1})[0].id;
                }catch (e){
                    throw "dont find kit " + akitNames;
                }
            }
            if(kitId==null){
                return null;
            }
            var kitRec;
            try{
                kitRec = record.load({
                    type:'kititem',
                    id:kitId
                });
            }catch (e){
                throw "dont find kit, id:" + kitId;
            }
            var result = [];

           var memberIndex = kitRec.getLineCount({
                sublistId: 'member'
            });

            for(var j = 0 ; j<memberIndex;j++){
                var resultObj = new Object();
                var sku = kitRec.getSublistText({
                    sublistId: 'member',
                    fieldId: 'item',
                    line: j
                });
                var internalid = kitRec.getSublistValue({
                    sublistId: 'member',
                    fieldId: 'item',
                    line: j
                });
                var quantity = kitRec.getSublistValue({
                    sublistId: 'member',
                    fieldId: 'quantity',
                    line: j
                });
                resultObj['sku'] = sku;
                resultObj['internalid'] = internalid;
                resultObj['quantity'] = quantity;
                //如果是用名字查kit  回传kit id
                if(akitId==null){
                    resultObj['kidId'] = kitId;
                }
                result[j] = resultObj;
            }
            return result;
        };

        /**
         *
         *
         * */
        method.item = new Object();
        method.item.getAttributeById= function(columns,id){
            var values = null;
            if(columns&&id){
                var search1 = search.create({
                    type:'item',
                    columns:columns,
                    filters:[['internalid','is',id],'AND',['type','is','Assembly']]
                }).run().each(function(ctx){
                    values = JSON.parse(JSON.stringify(ctx)).values;
                    return false;
                });
            }
            return values;
        };

        /**
         *
         *
         *
         * */
        method.store = new Object();
        method.store.getStoreInformation = function(params){
            var internalId = params['internalId'];
            var sellerId = params['sellerId'];
            var marketplaceId = params['marketplaceId'];
            var platform = params['platform'];
            var name = params['name'];
            var longname = params['longname'];

            var filter = [['custrecord_store_enabled','is','T']];
            if(internalId){
                filter[filter.length] = 'AND';
                filter[filter.length] = ['internalid','is',internalId];
            }

            if(sellerId){
                filter[filter.length] = 'AND';
                filter[filter.length] = ['custrecord_store_seller_id','is',sellerId];
            }

            if(marketplaceId){
                filter[filter.length] = 'AND';
                filter[filter.length] = ['custrecord_store_marketplace_id.custrecord_marketplace_code'
                    ,'is',marketplaceId];
            }

            if(platform){
                filter[filter.length] = 'AND';
                filter[filter.length] = ['custrecord_store_platform','anyof',platform];
            }

            if(name){
                filter[filter.length] = 'AND';
                filter[filter.length] = ['name','is',name];
            }

            var columns = ['name',{name:'internalid',join:'custrecord_store_location'},
                {name:"custrecord_marketplace_country",join:"custrecord_store_marketplace_id"},
                'custrecord_store_code'
            ];

            var hasSubsidiary =  false;
            try{
                var sub = search.create({
                    type : 'subsidiary'
                }).run().each(function(ctx){
                });
                hasSubsidiary = true;
            }catch (e){
                log.error({title:'e',details:e.message});
                hasSubsidiary = false;
            }

            if(hasSubsidiary){
                //columns[columns.length] = "custrecord_store_subsidiary";
                    //{name:"subsidiary",join:"custrecord_store_deparment"};
            }

            var result = new Object();
            log.debug({title:'store search',details:filter});
            var storeSearch = search.create({
                type:'customrecord_platform_store_information',
                columns:columns,
                filters:filter
            }).run().each(function(ctx){
                result.name = ctx.getValue('name');
                result.internalid = ctx.id;
                result.locationId = ctx.getValue({name:'internalid',join:'custrecord_store_location'});
                result.storeCode = ctx.getValue('custrecord_store_code');
                if(hasSubsidiary){
                    //result.subsidiaryId = ctx.getValue({name:"subsidiary",join:"custrecord_store_deparment"});
                    result.subsidiaryId = ctx.getValue("custrecord_store_subsidiary");
                }
                result.storeCountryId = ctx.getText({name:"custrecord_marketplace_country",join:"custrecord_store_marketplace_id"});
            });
            log.debug({title:'store information',
                details:'根据'+JSON.stringify(params)+'找到'+JSON.stringify(result)});
            return result;
        }
        return {
            method:method
        };
    });